package com.gogowan.agroenterprise.contorl;

import java.util.Hashtable;
import java.util.Map;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public abstract class MyAsyncTask {
	
	private Handler myHandler=null;
	private Thread myThread=null;
	
	public Thread getMyThread() {
		return myThread;
	}

	public void setMyThread(Thread myThread) {
		this.myThread = myThread;
	}

	public MyAsyncTask()
	{
		myHandler=new Handler(new AsyncCallback() {
			
			@Override
			public boolean handleMessage(Message msg) {
				// TODO Auto-generated method stub
				
				Map<String, Object> map=(Map<String, Object>)msg.getData().getSerializable("key");
				Object result=map.get("key");
				onPostExecute(result);
				return false;
				
				
			}
		});
		
	}
	
	private class AsyncCallback implements android.os.Handler.Callback
	{

		@Override
		public boolean handleMessage(Message msg) {
			// TODO Auto-generated method stub
			return false;
		}
		
	}
	
	private Object[] execparpams=null;
	
	public Object[] getExecparpams() {
		return execparpams;
	}

	public void setExecparpams(Object[] execparpams) {
		this.execparpams = execparpams;
	}

	@SuppressWarnings({"UnusedDeclaration"})
	protected  void onPostExecute(Object res) {
	}
	@SuppressWarnings({"UnusedDeclaration"})
	protected Object doInBackground(Object... params) {
		return null;
	}
	
	public final void execute(Object... params)
	{
		setExecparpams(params);
		Thread th=new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Object result =doInBackground(getExecparpams());
				if(result==null)
					result="";
				Message msg=new Message();
				Hashtable<String, Object> hashTable=new Hashtable<String, Object>();
				hashTable.put("key", result);
				Bundle bundle=new Bundle();
				bundle.putSerializable("key", hashTable);
				msg.setData(bundle);
				myHandler.sendMessage(msg);
			}
		});
		th.start();
		//th.destroy();
	}
	
	public synchronized final void Cancel()
	{
		if(getMyThread()!=null)
		{
			if(getMyThread().isInterrupted());
				getMyThread().interrupt();
		}
	}
}
